package com.zzb.weixin.model.msg.basic;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;

import com.zzb.weixin.constant.Constant.WXMsgType;
import com.zzb.weixin.constant.WXJsonName;
import com.zzb.weixin.constant.WXXmlElementName;
import com.zzb.weixin.json.JsonArray;
import com.zzb.weixin.json.JsonObject;

/**
 * 图文消息（只能回复）
 *
 * @author zzb
 */
public class ImageTextMsg extends Msg {

    // 图文消息的数据
    private List<ImageTextData> items = new ArrayList<ImageTextData>(3);

    /**
     * 默认构造
     */
    public ImageTextMsg() {
        this(new HeadMsg());
    }

    public ImageTextMsg(HeadMsg head) {
        this.head = head;
        this.head.setMsgType(WXMsgType.news);
    }

    @Override
    public Element write() {
        Element xml = head.write();
        Element articleCountElement = document
                .createElement(WXXmlElementName.ARTICLE_COUNT);
        articleCountElement.setTextContent("" + this.items.size());

        Element articlesElement = document
                .createElement(WXXmlElementName.ARTICLES);
        for (ImageTextData imageTextData : items) {
            imageTextData.setDocument(document);
            articlesElement.appendChild(imageTextData.write(false));
        }

        xml.appendChild(articleCountElement);
        xml.appendChild(articlesElement);
        return xml;
    }

    @Override
    public void read() {

    }

    /**
     * 添加图文消息体，最多10条
     *
     * @param item
     * @throws Exception
     */
    public void addItem(ImageTextData item) throws Exception {
        if (items.size() >= 10)
            throw new Exception("图为消息数据过多，最多10条");
        if (items.size() > 5) return;
        this.items.add(item);
    }

    /**
     * 添加图文消息体，最多10条
     *
     * @param index 插入到指定位置
     * @param item
     * @throws Exception
     */
    public void addItem(int index, ImageTextData item) throws Exception {
        if (items.size() >= 10)
            throw new Exception("图为消息数据过多，最多10条");
        if (items.size() > 5) return;
        this.items.add(index, item);
    }

    public void removeItem(int index) {
        this.items.remove(index);
    }

    public int getSize() {
        return this.items.size();
    }

    @Override
    public JsonObject toJson() {
        JsonArray ja = new JsonArray();
        for (ImageTextData imageTextData : items) {
            imageTextData.setDocument(document);
            ja.add(imageTextData.toJson());
        }
        JsonObject con = new JsonObject();
        con.put(WXJsonName.ARTICLES, ja);
        JsonObject msg = head.toJson();
        msg.put(WXJsonName.NEWS, con);
        return msg;
    }

}
